<template>
	<view class="page-container">
		<view class="header">
			<x-status-bar></x-status-bar>
			<view class="flex-center-between header-navbar">
				<view class="flex-center clear-flex" @click="getArea">
					<view class="clear-flex color-white linecamp-1" style="width: 100rpx">
						{{ areaFormat || lang_index.selectCity }}
					</view>
					<u-icon name="right" custom-prefix="u" color="#FFFFFF" size="32"></u-icon>
				</view>
				<view class="search-container flex-center" style="margin: 0 16rpx;width: 100%;"
					@click="jumpUrl('/pages/user/index/search/index/index')">
					<image src="@/static/image/common/search.png" style="width: 32rpx; height: 32rpx"
						class="clear-flex u-m-r-14"></image>
					<view class="color-grew linecamp-1">{{ lang_index.searchTips }}</view>
				</view>
				<message-btn></message-btn>
			</view>
		</view>

		<view class="container">
			<view v-if="bannerList.length" class="header-bg"></view>
			<view v-if="bannerList.length" style="padding: 10rpx 30rpx 0;" class="banner-container">
				<u-swiper :list="bannerList" mode="none" height="290" @click="bannerClickAction(bannerList[$event])"></u-swiper>
			</view>

			<view v-if="noticeList.length" style="padding: 16rpx 30rpx 0;background: #FFFFFF" class="notice-bar-container bg-white">
				<notice-bar textKey="title" :list="noticeList"></notice-bar>
			</view>

			<view class="u-p-t-18 bg-white menu-container">
				<menu-list :list="menusOrigin"></menu-list>
			</view>

			<view style="padding: 26rpx 30rpx 0;" class="hot-shop-container">
				<view class="flex-center-between">
					<view class="u-f-38 u-lh-52 font-medio linecamp-1">{{lang_index.popularShopRecommend}}</view>
					<x-see-more v-if="hotShopList.length === 3" class="nowrap" @click="jumpUrl('/pages/user/shop/hot/list')"></x-see-more>
				</view>
				<view class="u-p-t-10">
					<shop-card  v-for="(item, index) in hotShopList" :key="index" :class="[index ? 'u-m-t-14' : '']"
						@click="jumpUrl(`/pages/user/comerciante/detail/detail?merchantId=${ item.merchantId }`)" instance :item="item" @phone="settingValue = 'contact'"></shop-card>
					<mescroll-empty v-if="!hotShopList.length"></mescroll-empty>
				</view>
			</view>
			
			<view>
				<view class="shop-tab-container" style="padding: 20rpx 30rpx 20rpx;">
					<scroll-view scroll-x style="width: 100%;">
						<view class="flex-center">
							<view v-for="(item, index) in tabs" :key="index" :class="['tab-item clear-flex',
							index ? 'u-m-l-60' : '',
							tabIndex === index ? 'u-f-38 u-lh-52 font-medio' : 'u-f-32 u-lh-44']" @click="changeTabAction(index)">
								<view>{{ item.title }}</view>
								<view v-if="tabIndex === index" class="tab-item-line"></view>
							</view>
						</view>
					</scroll-view>
				</view>

				<mescroll-body height="100%" ref="mescrollRef"
					@init="mescrollInit" @down="downCallback" @up="upCallback">
					<view>
						<view class="u-m-t-18" style="padding: 0 30rpx;">
							<view v-for="(item, index) in dataList" :key="index" :class="[index ? 'u-m-t-14' : '']"
								@click="jumpUrl(`/pages/user/comerciante/detail/detail?merchantId=${ item.merchantId }`)">
								<shop-card instance :item="item" @phone="settingValue = 'contact'"></shop-card>
							</view>
						</view>

						<!-- 留空 -->
						<view style="height: 200rpx;"></view>
					</view>
				</mescroll-body>
			</view>
		</view>

		<!-- 未开启定位提示 -->
		<permission-unAuthTips v-model="settingValue"></permission-unAuthTips>

		<!-- 购物车按钮 -->
		<view class="cart-btn">
			<image src="@/static/image/index/cart.png" style="width: 126rpx; height: 126rpx"
				@click="jumpUrl('/pages/user/shop/cart/cart')"></image>
				
			<view v-if="cartCount" class="cart-btn-count u-f-20 u-lh-28 font-bold flex-center-center">{{ cartCount || 0 }}</view>
		</view>
	</view>
</template>

<script>
	import permision from "@/utils/permission.js"
	import NoticeBar from './components/notice-bar'
	import MenuList from './components/menu-list'
	import {
		merchantPage
	} from '@/api/user/merchant.js'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";

	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: { NoticeBar, MenuList },
		data() {
			// 初始化菜单栏
			let menusOrigin = [
				{ label: '秒杀', key: 'rushing', page: '/pages/user/shop/list/rush' },
				{ label: '拼团', key: 'collage', page: '/pages/user/shop/list/collage' },
				{ label: '预售', key: 'preSale', page: '/pages/user/shop/list/presale' },
				{ label: '探店笔记', key: 'shopNote', page: '/pages/user/note/list/list' },
				{ label: '任务赚钱', key: 'taskEarn', page: '/pages/user/personal/score/score' },
				{ label: '游戏', key: 'game', page: '' },
			].map((item, index) => ({
				...item,
				icon: require(`@/static/image/index/menu_icon${ index + 1 }.png`)
			}))
			return {
				menusOrigin,

				tabIndex: 0,
				timer: null,
				interval: null,

				area: {},

				settingValue: '',

				hotShopList: [],
				dataList: []
			}
		},
		computed: {
			// 当前地址
			localAddress() {
				return this.$store.state.user.localAddress
			},
			// 获取轮播图
			bannerList() {
				return this.$store.state.user.bannerList
			},
			// 获取公告列表
			noticeList() {
				return this.$store.state.user.noticeList
			},
			// 获取商家分类
			tabs() {
				let list = this.$store.state.common.shopCategory
				return [{
					title: this.lang_common.all
				}, ...list]
			},
			areaFormat() {
				let str = '',
					area = this.localAddress
				for (let key in area) {
					let item = area[key]
					item && item.title && (str += (item.title + ','))
				}
				str && (str = str.slice(0, -1))
				return str
			}
		},
		onPullDownRefresh() {
			clearTimeout(this.timer)
			this.timer = setTimeout(() => {
				this.initPageData()
				uni.stopPullDownRefresh()
			}, 1000)
		},
		async onLoad() {
			this.authContact();
			// 每次首次进来都进行订阅是否开启定位
			let locationPermission = await this.authLocation(1)
			if (!locationPermission) {
				this.settingValue = 'location'
			} else {
				this.$store.commit('UPDATE_LOCATION_STATUS', 1)
				this.initLocation()
				clearInterval(this.interval)
				this.interval = setInterval(() => {
					this.initLocation()
				}, 5000)
			}
			clearTimeout(this.timer)
			this.timer = setTimeout(() => {
				clearTimeout(this.timer)
				this.$store.commit('UPDATE_TABBAR_VISIBLE_TYPE', 'user')
			}, 100)
		},
		onShow() {
			if (this.locationStatus === 1) {
				this.initLocation()
				clearInterval(this.interval)
				this.interval = setInterval(() => {
					this.initLocation()
				}, 5000)
			}
			this.initPageData()
		},
		methods: {
			// 初始化获取位置信息
			initLocation() {
				// 优先查询是否已经获取位置信息权限
				uni.getLocation({
					isHighAccuracy: true,
					success: res => {
						let {
							latitude,
							longitude
						} = res
						this.$store.commit('UPDATE_LOCATION_LATLNG', `${ latitude },${ longitude }`)
						// console.log(res)
						// 根据谷歌地址逆解析获取位置信息
						// if (!this.area.country) {
						// 	uni.request({
						// 		url: `https://maps.googleapis.com/maps/api/geocode/json?latlng=${ latitude + ',' + longitude }&key=AIzaSyChCQz3h6vKujgTS8PHYaNolxKNgmWrKWo`,
						// 		success: ({ data }) => {
						// 			// 使用plus_code，待商榷
						// 			this.area.country = '1'
						// 		}
						// 	})
						// }
					}
				})
			},
			
			// 修改定位信息
			getArea() {
				uni.navigateTo({
					url: '/pages/other/city/city',
					events: {
						change: res => {
							this.$store.commit('UPDATE_USER_LOCAL_ADDRESS', res)
						}
					},
					success: res => {
						res.eventChannel.emit('city-page', this.localAddress)
					}
				})
			},
			initPageData() {
				this.getHotShopList()
				this.downCallback()
			},
			// tab发生变动后
			changeTabAction(index) {
				this.tabIndex = index
				let domlist = ['hot-shop-container', 'menu-container', 'header', 'notice-bar-container', 'banner-container']
				domlist = domlist.map(item => {
					return this.query('.' + item)
				})
				Promise.all(domlist).then((res) => {
					let height = 0
					res.map(item => {
						if (item) {
							height += item.height
						}
					})
					let scrollObj = {}
					if (plus.os.name == "iOS") {
						scrollObj.duration = 0
					}
					uni.pageScrollTo({
						scrollTop: height - uni.upx2px(98) - this.status_bar_height,
						...scrollObj
					})
					clearTimeout(this.timer)
					this.timer = setTimeout(() => {
						clearTimeout(this.timer)
						this.downCallback(1)
					}, 1000)
				})
			},
			// 获取商家
			getShopList(option = {}) {
				return new Promise(resolve => {
					merchantPage({
						pageNumber: 1,
						pageSize: 10,
						...option
					}).then(result => {
						resolve(result)
					}).catch(e => {
						resolve({
							list: []
						})
					})
				})
			},
			// 获取热门商家列表
			async getHotShopList() {
				let {
					list
				} = await this.getShopList({
					pageSize: 3,
					isRecommend: 1
				})
				console.log('hotlist => ', list)
				this.hotShopList = list
			},
			/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
			upCallback(page) {
				let node = this.$refs['mescrollRef']
				let queryObj = {}
				if (this.tabIndex) {
					queryObj.categoryId = this.tabs[this.tabIndex].categoryId
				}
				merchantPage({
					pageNumber: page.num,
					pageSize: page.size,
					...queryObj
				}).then(res => {
					node && node.mescroll.endSuccess(res.list.length);
					if (page.num == 1) this.dataList = []; //如果是第一页需手动制空列表
					this.dataList = this.dataList.concat(res.list); //追加新数据
					let { dispatch } = this.$store
					// 初始化banner
					dispatch('initBanner')
					// 用户-初始化公告列表信息
					dispatch('initNotice')
					// 初始化分类列表
					dispatch('initCategory', 1)
				}).catch(() => {
					node && node.mescroll.endErr();
				})
			},
			downCallback() {
				let node = this.$refs['mescrollRef']
				node && node.mescroll.resetUpScroll()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.header {
		background: linear-gradient(to right, #F94404 0%, #FD164F 100%);

		&-bg {
			@extend .header;
			position: absolute;
			top: 0;
			left: 0;
			height: calc(302rpx + var(--status-bar-height));
			width: 100%;
		}
	}

	.search-container {
		max-width: 460rpx;
		height: 66rpx;
		padding: 10rpx 16rpx;
		border-radius: 100rpx;
		background-color: #F6F6F6;
	}

	.container {
		background: linear-gradient(to bottom, #FFFFFF 0%, #F9F9F9 100%);
	}

	.shop-tab-container {
		position: sticky;
		top: calc(var(--status-bar-height) + 98rpx);
		left: 0;
		z-index: 999999;
		background-color: #FFFFFF;
	}

	.tab-item {
		position: relative;
		z-index: 0;

		&-line {
			position: absolute;
			left: 50%;
			bottom: 2rpx;
			transform: translateX(-50%);
			z-index: -1;
			width: 84rpx;
			height: 12rpx;
			background: linear-gradient(to bottom, #FE4E77 0%, #FC2642 100%);
			;
		}
	}

	.cart-btn {
		position: fixed;
		bottom: 200rpx;
		right: 12rpx;
		z-index: 999999;
		
		&-count {
			position: absolute;
			top: 4rpx;
			right: 8rpx;
			width: 32rpx;
			height: 32rpx;
			color: #FC2642;
			background: #FFFFFF;
			border: 2rpx solid #FC2642;
			border-radius: 100rpx;
		}
	}
</style>
